package com.haruhi.bot.endpoint.ws.config;

import lombok.Data;
import org.apache.logging.log4j.util.Strings;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.PostConstruct;
import java.net.URI;
import java.util.Collections;
import java.util.List;

@Component
@Data
@ConfigurationProperties(prefix = "ws")
public class EndpointConfiguration {

    private List<Client> clients;
    private List<Server> servers;

    @Data
    public static class Client{
        private String scheme;
        private String host;
        private String port;
        private String path;
        private String accessToken;
        private long reconnectPeriod;
        private URI uri;
        private HttpHeaders httpHeaders = new HttpHeaders();

    }

    @Data
    public static class Server{
        private String path;
        private String accessToken;
        private Integer maxConnections;

    }

    @PostConstruct
    private void initClients(){
        if (!CollectionUtils.isEmpty(clients)) {
            for (Client client : clients) {
                client.setUri(URI.create((client.getScheme() + "://" + client.getHost() + ":" + client.getPort() + client.getPath()).replace(" ","")));
                if(Strings.isNotBlank(client.getAccessToken())){
                    client.getHttpHeaders().put(HttpHeaders.AUTHORIZATION, Collections.singletonList("Token " + client.getAccessToken()));
                }
            }
        }
    }

}
